<template>
	<el-aside width="220px" class="image-aside" v-loading="loading">
		<div class="top">
			<AsideList :active="activeId == item.id" v-for="(item, index) in list" :key="index" @edit="handleEdit(item)"
				@delete="handleDelete(item.id)" @click="handleChangeActiveId(item.id)">
				{{ item.name }}
			</AsideList>
		</div>
		<div class="bottom">
			<el-pagination background layout="prev,next" :total="total" :current-page="currentPage" :page-size="limit"
				@current-change="getData" />
		</div>
	</el-aside>

	<FormDrawer :title="drawerTitle" ref="formDrawerRef" @submit="handleSumbit">
		<el-form :model="form" ref="formRef" :rules="rules" label-width=" 80px" :inline="false">
			<el-form-item label="分类名称" prop="name">
				<el-input v-model="form.name"></el-input>
			</el-form-item>
			<el-form-item label="排序" prop="order">
				<el-input-number v-model="form.order" :min="0" :max="1000" />
			</el-form-item>
		</el-form>
	</FormDrawer>
</template>

<script setup>
	import AsideList from '~/components/AsideList.vue';
	import {
		getImageClassList,
		creatImageClass,
		updateImageClass,
	} from '~/api/image_class';
	import {
		reactive,
		ref,
		nextTick,
		computed
	} from 'vue';
	import FormDrawer from './FormDrawer.vue';
	import {
		toast
	} from '~/composables/util.js';
	import {
		deleteImageclass
	} from '../api/image_class';

	const loading = ref(false);
	const list = ref([]);
	const activeId = ref(0);

	const currentPage = ref(1);
	const total = ref(0);
	const limit = ref(10);

	function getData(p = null) {
		if (typeof p === 'number') {
			currentPage.value = p;
		}

		loading.value = true;
		getImageClassList(currentPage.value)
			.then((res) => {
				total.value = res.totalCount;
				list.value = res.list; // 假设接口返回的数据结构中有 list 字段
				const item = list.value[0];
				if (item) {
					handleChangeActiveId(item.id)
				}
			})
			.catch((error) => {
				console.error('获取图库分类列表失败:', error);
				toast('获取图库分类列表失败，请检查网络或重试');
			})
			.finally(() => {
				loading.value = false;
			});
	}
	getData();

	const editId = ref(0);
	const drawerTitle = computed(() => (editId.value ? '修改' : '新增'));
	const formDrawerRef = ref(null);

	const form = reactive({
		name: '',
		order: 50,
	});

	const rules = {
		name: [{
			required: true,
			message: '图库分类名称不能为空',
			trigger: 'blur',
		}, ],
	};

	const formRef = ref(null);
	const handleSumbit = () => {
		formRef.value.validate((valid) => {
			if (!valid) return;
			if (editId.value) {
				// 执行修改操作
				updateImageClass({
						...form,
						id: editId.value,
					})
					.then((res) => {
						toast('修改成功');
						getData(currentPage.value);
						formDrawerRef.value.close();
					})
					.catch((error) => {
						console.error('修改图库分类失败:', error);
						toast('修改图库分类失败，请检查网络或重试');
					})
					.finally(() => {
						formDrawerRef.value.hideloading && formDrawerRef.value.hideloading();
					});
			} else {
				// 执行新增操作
				creatImageClass(form)
					.then((res) => {
						toast('新增成功');
						getData(1);
						formDrawerRef.value.close();
					})
					.catch((error) => {
						console.error('新增图库分类失败:', error);
						toast('新增图库分类失败，请检查网络或重试');
					})
					.finally(() => {
						formDrawerRef.value.hideloading && formDrawerRef.value.hideloading();
					});
			}
		});
	};

	const handleCreate = async () => {
		editId.value = 0;
		form.name = '';
		form.order = 50;
		await nextTick(); // 确保组件挂载完成
		if (formDrawerRef.value) {
			formDrawerRef.value.open();
		} else {
			console.error('FormDrawer ref is not initialized.');
		}
	};

	const handleEdit = (row) => {
		editId.value = row.id;
		form.name = row.name;
		form.order = row.order;
		formDrawerRef.value.open();
	};

	const handleDelete = (id) => {
		loading.value = true;
		deleteImageclass(id)
			.then((res) => {
				toast('删除成功');
				getData();
			})
			.catch((error) => {
				console.error('删除图库分类失败:', error);
				toast('删除图库分类失败，请检查网络或重试');
			})
			.finally(() => {
				loading.value = false;
			});
	};

	const emit = defineEmits(["change"])

	function handleChangeActiveId(id) {
		activeId.value = id;
		emit("change",id)
	}

	defineExpose({
		handleCreate,
	});
</script>

<style scoped>
	.image-aside {
		border-right: 1px solid #eeeeee;
		position: relative;
	}

	.image-aside .top {
		position: absolute;
		top: 0;
		right: 0;
		left: 0;
		bottom: 50px;
		overflow-y: auto;
	}

	.image-aside .bottom {
		position: absolute;
		bottom: 0;
		height: 50px;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>